package pc

import (
	"fmt"
	"os"
	"strconv"
	"strings"
	"tcsc/controllers/mobile"
	"tcsc/models"
	"tcsc/sword"
	"time"

	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	// "github.com/astaxie/beego/utils"
)

// "sword"

type My struct {
	BaseController
}

func (c *My) Get() {
	var w []string
	w = append(w, `a.status=1`)
	w = append(w, `a.censoring=1`)
	ob := ` order by a.recommend desc,a.sort desc `
	page, _, num := models.Pagechange(c.GetString("page"), "4")
	lt := ` limit ` + page + `,` + num
	ws := strings.Join(w, ` and `)
	recommend := mobile.ProductList(`select a.title,a.price,a.isvip,a.gid,a.id,b.pathname 
		from mt_product a 
		left join mt_resources b on a.img=b.id 
		where `+ws+ob+lt, c.Uid)
	if c.IsAjax() {
		c.Data["json"] = recommend
		c.ServeJSON()
	} else {
		info := models.Query(`select a.integral,a.mobile,a.id,a.monicker,a.money,a.type,a.driver,b.pathname,c.name as vname,d.pathname as vpath 
		from mt_member a
	 	left join mt_resources b on a.avatar=b.id 
	 	left join mt_member_vip c on a.vip=c.id 
	 	left join mt_resources d on c.img=d.id
	  	where a.id=` + c.Uid)[0]
		c.Data["recommend"] = recommend
		c.Data["info"] = info
		c.Data["focus"] = models.Query(`select count(a.id) as num from mt_member_focus a where a.uid=` + c.Uid)[0]["num"]
		c.Data["collectnum"] = models.Query(`select count(a.id) as num from mt_member_collection a where a.uid=` + c.Uid)[0]["num"]
		c.Data["collect"] = mobile.ProductList(`select b.id,b.title,c.pathname,b.price,b.isvip,b.gid 
		from mt_member_collection a 
		join mt_product b on a.pid=b.id 
		left join mt_resources c on b.img=c.id 
		where a.uid=`+c.Uid+` 
		order by a.addtime desc 
		limit 10`, c.Uid)
		order1 := models.Query(`select count(a.id) as num from mt_order a where a.status=1 and a.uid=` + c.Uid)[0]["num"].(string)
		c.Data["order1"] = order1
		c.Data["order2"] = models.Query(`select count(a.id) as num from mt_order a where a.status=2 and a.uid=` + c.Uid)[0]["num"]
		c.Data["order3"] = models.Query(`select count(a.id) as num from mt_order a where a.status=3 and a.uid=` + c.Uid)[0]["num"]
		c.Data["order4"] = models.Query(`select count(a.id) as num from mt_order a where a.status=4 and a.uid=` + c.Uid)[0]["num"]
		c.Data["coupon"] = models.Query(`select count(a.id) as num from mt_member_coupon a where a.status=1 and a.uid=` + c.Uid)[0]["num"]
		c.Data["foot"] = mobile.ProductList(`select b.id,b.title,c.pathname,b.price,a.addtime,b.isvip,b.gid 
		from mt_systems_reading a 
		join mt_product b on a.pid=b.id 
		left join mt_resources c on b.img=c.id 
		where a.uid=`+c.Uid+` 
		order by a.addtime desc 
		limit 2`, c.Uid)
		order := models.Query(`select ordernum,carid,id 
		from mt_order 
		where status=1 and uid=` + c.Uid + ` 
		order by addtime desc 
		limit 1`)
		if order != nil {
			carid := fmt.Sprint(order[0]["carid"])
			shopcar := models.Query(`select a.pid,b.title,a.price,a.num,c.pathname 
			from mt_order_car a 
			left join mt_product b on a.pid=b.id 
			left join mt_resources c on b.img=c.id 
			where a.id in(` + carid + `)`)
			order[0]["shopcar"] = shopcar
			c.Data["order"] = order[0]
			if order1 == "1" {
				c.Data["order11"] = "0"
			} else {
				c.Data["order11"] = strings.Split(sword.Cut(order1, "1"), ".")[0]
			}
		}
		c.TplName = "pc/my/index.html"
	}
}

type MyOrder struct {
	BaseController
}

func (c *MyOrder) Get() {
	beego.Debug(111)
	var w []string
	w = append(w, `a.uid=`+c.Uid)
	w = append(w, `a.status>0`)
	status := c.GetString("status")
	ordernum := c.GetString("ordernum")
	if ordernum != "" {
		w = append(w, `a.ordernum like '%`+ordernum+`%'`)
		status = ""
	} else {
		if status != "" {
			w = append(w, `a.status=`+status)
		}
	}
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.addtime desc`
	ws := strings.Join(w, ` and `)
	sql := `select a.gid,a.id,a.money,a.count,a.carid,a.status,a.type,a.goodtime,a.agid,b.name,a.addtime,a.ordernum 
	from mt_order a 
	left join mt_shop b on a.gid=b.id 
	where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_order a where ` + ws
	info := models.Query(sql)
	c.Data["paginator"] = models.Page(sql2, page2, num)
	if ordernum != "" {
		var pids []string
		product := models.Query(`select id from mt_product where title like '%` + ordernum + `%'`)
		for _, v := range product {
			pids = append(pids, v["id"].(string))
		}
		if len(pids) > 0 {
			pidss := strings.Join(pids, ",")
			var carid []string
			ordercar := models.Query(`select id from mt_order_car where uid=? and pid in(`+pidss+`) and status>1`, c.Uid)
			for _, v := range ordercar {
				carid = append(carid, v["id"].(string))
			}
			for _, v := range carid {
				info2 := models.Query(`
				select a.gid,a.id,a.money,a.count,a.carid,a.status,a.type,a.goodtime,a.agid,b.name,a.addtime,a.ordernum 
				from mt_order a 
				left join mt_shop b on a.gid=b.id 
				where a.uid=? and a.status>0 and concat(',',a.carid,',') like '%`+v+`%'`, c.Uid)
				for _, i := range info2 {
					info = append(info, i)
				}
			}

		}

	}

	for _, v := range info {
		carid := fmt.Sprint(v["carid"])
		status := fmt.Sprint(v["status"])
		shopcar := models.Query(`select a.gid,a.pid,a.num,a.sendnum,a.status,b.title,b.spec,b.number,a.price,c.pathname,b.model,a.spec as spec2,b.width,b.length,b.height,b.weight  
			from mt_order_car a 
			left join mt_product b on a.pid=b.id 
			left join mt_resources c on b.img=c.id 
			where a.id in(` + carid + `)`)
		var tj = "0.00"
		var zl = "0.00"
		var sl = 0
		for _, v := range shopcar {
			if fmt.Sprint(v["spec2"]) == "0" {
				v["price"] = sword.Mult(v["price"].(string), v["number"].(string))
			}
			width := fmt.Sprint(v["width"])
			length := fmt.Sprint(v["length"])
			height := fmt.Sprint(v["height"])
			weight := fmt.Sprint(v["weight"])
			number := fmt.Sprint(v["number"])
			num := fmt.Sprint(v["num"])
			numi, _ := strconv.Atoi(num)
			tjone := sword.Divi(sword.Mult(width, sword.Mult(height, sword.Mult(length, num))), "1000000")
			tj = sword.Sum(tj, tjone)
			sl += numi
			zlone := sword.Mult(sword.Mult(weight, number), num)
			zl = sword.Sum(zl, zlone)
		}
		v["tj"] = tj
		v["zl"] = sword.Divi(zl, "1000")
		v["sl"] = sl
		v["shopcar"] = shopcar
		var isre = 0
		goodtime := fmt.Sprint(v["goodtime"])
		if status == "4" || status == "5" {
			var t int
			freight, _ := strconv.Atoi(fmt.Sprint(models.Systems()["freight"]))
			exile, _ := strconv.Atoi(fmt.Sprint(models.Systems()["exile"]))
			if freight > exile {
				t = freight
			} else {
				t = exile
			}
			timenow := time.Now().Local()
			loc, _ := time.LoadLocation("Local")
			timegood, _ := time.ParseInLocation(Tparse, goodtime, loc)
			timegood = timegood.AddDate(0, 0, t)
			if timenow.Before(timegood) {
				isre = 1
			}
		}
		v["isre"] = isre
		if status == "6" {
			v["return"] = models.Query("select * from mt_order_return where status=1 and oid=" + v["id"].(string))[0]
		}
	}
	c.Data["info"] = info
	c.Data["status"] = status
	c.Data["url"] = "/my/order?status=" + status + "&ordernum=" + ordernum + "&"
	mem := models.Query(`select money,paypassword as token,wx_openid_gzh,wx_openid_xapp,wx_openid_app from mt_member where id=` + c.Uid)[0]
	c.Data["mem"] = mem
	c.TplName = "pc/my/order/index.html"
}

type MyOrderExcel struct {
	BaseController
}

func (c *MyOrderExcel) Get() {
	id := c.GetString("id")
	info := models.Query(`select ordernum,carid from mt_order where uid=? and id=?`, c.Uid, id)
	if info == nil {
		return
	}
	xlsx := excelize.NewFile()
	// index := xlsx.NewSheet("Sheet1")

	xlsx.SetCellValue("Sheet1", "A1", "产品名称")
	xlsx.SetCellValue("Sheet1", "B1", "条形码")
	xlsx.SetCellValue("Sheet1", "C1", "产品型号")
	xlsx.SetCellValue("Sheet1", "D1", "装箱数")
	xlsx.SetCellValue("Sheet1", "E1", "体积(立方)")
	xlsx.SetCellValue("Sheet1", "F1", "重量(kg)")
	xlsx.SetCellValue("Sheet1", "G1", "数量")
	xlsx.SetCellValue("Sheet1", "H1", "单价")
	xlsx.SetCellValue("Sheet1", "I1", "总价")
	shopcar := models.Query(`select a.gid,a.pid,a.num,a.sendnum,a.status,b.title,b.spec,b.number,b.barcode,a.price,c.pathname,b.model,a.spec as spec2,b.width,b.length,b.height,b.weight  
			from mt_order_car a 
			left join mt_product b on a.pid=b.id 
			left join mt_resources c on b.img=c.id 
			where a.id in(` + fmt.Sprint(info[0]["carid"]) + `)`)

	for k, v := range shopcar {
		k += 2
		xlsx.SetCellValue("Sheet1", "H"+fmt.Sprint(k), v["price"])
		if fmt.Sprint(v["spec2"]) == "0" {
			v["price"] = sword.Mult(v["price"].(string), v["number"].(string))
		}
		width := fmt.Sprint(v["width"])
		length := fmt.Sprint(v["length"])
		height := fmt.Sprint(v["height"])
		weight := fmt.Sprint(v["weight"])
		number := fmt.Sprint(v["number"])
		num := fmt.Sprint(v["num"])

		tjone := sword.Divi(sword.Mult(width, sword.Mult(height, sword.Mult(length, num))), "1000000")
		zlone := sword.Divi(sword.Mult(sword.Mult(weight, number), num), "1000")
		xlsx.SetCellValue("Sheet1", "A"+fmt.Sprint(k), v["title"])
		xlsx.SetCellValue("Sheet1", "B"+fmt.Sprint(k), v["barcode"])
		xlsx.SetCellValue("Sheet1", "C"+fmt.Sprint(k), v["model"])
		xlsx.SetCellValue("Sheet1", "D"+fmt.Sprint(k), v["number"])
		xlsx.SetCellValue("Sheet1", "E"+fmt.Sprint(k), tjone)
		xlsx.SetCellValue("Sheet1", "F"+fmt.Sprint(k), zlone)
		xlsx.SetCellValue("Sheet1", "G"+fmt.Sprint(k), num)
		xlsx.SetCellValue("Sheet1", "I"+fmt.Sprint(k), sword.Mult(num, fmt.Sprint(v["price"])))
	}

	// nowtimes := fmt.Sprint(time.Now().Unix())
	err := os.MkdirAll("static/xlsx", 0777)
	if err != nil {
		beego.Debug(err)
		return
	}
	ordernum := fmt.Sprint(info[0]["ordernum"])
	err = xlsx.SaveAs("static/xlsx/" + ordernum + ".xlsx")
	if err != nil {
		beego.Debug(err)
		return
	}
	c.Ctx.Redirect(302, "/static/xlsx/"+ordernum+".xlsx")
}

type MyEvaluation struct {
	BaseController
}

func (c *MyEvaluation) Get() {
	var w []string
	w = append(w, `a.status=1`)
	w = append(w, `a.censoring=1`)
	w = append(w, `a.sid=0`)
	ws := strings.Join(w, ` and `)
	ob := ` order by a.addtime desc `
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	sql := `select a.id,a.score,a.img,a.addtime,a.content,c.pathname,b.monicker,d.pid,e.title,e.price,f.pathname as ppath,d.num 
	from mt_product_evaluation a 
	left join mt_member b on a.uid=b.id 
	left join mt_resources c on b.avatar=c.id 
	join (select * from mt_order_car where uid=` + c.Uid + `) d on a.cid=d.id 
	left join mt_product e on d.pid=e.id 
	left join mt_resources f on e.img=f.id 
	where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_product_evaluation a 
	join (select * from mt_order_car where uid=` + c.Uid + `) d on a.cid=d.id where ` + ws
	info := models.Query(sql)
	c.Data["paginator"] = models.Page(sql2, page2, num)
	for _, v := range info {
		v["price"] = sword.Mult(fmt.Sprint(v["price"]), models.Systems()["mult"].(string))
		var fold string
		mem := models.Query(`select b.fold from mt_member a left join mt_member_vip b on a.vip=b.id where a.id=` + c.Uid)[0]
		if fold = fmt.Sprint(mem["fold"]); fold != "" && fold != "<nil>" {
			v["price"] = sword.Divi(sword.Mult(fmt.Sprint(v["price"]), fold), "100")
		}
		if img := fmt.Sprint(v["img"]); img != "" && img != "<nil>" {
			v["imgs"] = models.Query(`select pathname from mt_resources where id in(` + img + `)`)
		}
	}
	c.Data["info"] = info
	c.Data["url"] = "/my/evaluation?"
	c.TplName = "pc/my/order/evaluation.html"
}

type MyFoot struct {
	BaseController
}

func (c *MyFoot) Get() {
	var w []string
	w = append(w, `a.uid=`+c.Uid)
	w = append(w, `a.pid>0`)
	w = append(w, `a.status=1`)
	ob := ` order by a.addtime desc`
	ws := strings.Join(w, ` and `)
	sql := `select a.id,b.title,a.pid,c.pathname,b.price,b.minbuy,a.addtime 
	from mt_systems_reading a 
	join mt_product b on a.pid=b.id 
	left join mt_resources c on b.img=c.id 
	where ` + ws + ob
	info := models.Query(sql)
	for _, v := range info {
		v["price"] = sword.Mult(fmt.Sprint(v["price"]), models.Systems()["mult"].(string))
		if fmt.Sprint(v["isvip"]) == "1" {
			var fold string
			mem := models.Query(`select b.fold from mt_member a left join mt_member_vip b on a.vip=b.id where a.id=` + c.Uid)[0]
			if fold = fmt.Sprint(mem["fold"]); fold != "" && fold != "<nil>" {
				v["vprice"] = sword.Divi(sword.Mult(fmt.Sprint(v["price"]), fold), "100")
			}
		}
	}
	c.Data["info"] = info
	c.TplName = "pc/my/cf/foot.html"
}

func (c *MyFoot) Post() {
	defer c.ServeJSON()
	id := c.GetString("id")
	if id == "" {
		if err := models.Exec(`update mt_systems_reading set status=0 where pid>0 and uid=` + c.Uid); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {
			c.Data["json"] = 1
		}
	} else {
		if err := models.Exec(`update mt_systems_reading set status=0 where id=` + id); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {
			c.Data["json"] = 1
		}
	}
}

type MyAddress struct {
	BaseController
}

func (c *MyAddress) Get() {
	address := models.Query(`select a.name,a.mobile,a.default,a.id,a.address,b.name as shen,c.name as shi,d.name as qu,a.province,a.city,a.area 
		from mt_member_address a 
		left join mt_area b on a.province=b.code 
		left join mt_area c on a.city=c.code 
		left join mt_area d on a.area=d.code 
		where a.status=1 and a.uid=` + c.Uid + ` 
		order by a.addtime desc`)
	c.Data["info"] = address
	if Bm.IsExist("area") {
		c.Data["province"] = Bm.Get("area")
	} else {
		AreaGet()
		c.Data["province"] = Bm.Get("area")
	}
	c.TplName = "pc/my/info/address.html"
}

func (c *MyAddress) Post() {
	input := c.Input()
	id := input.Get("id")
	input.Set("uid", c.Uid)
	if id == "" {
		if isdefault := models.Query(`select id from mt_member_address where uid=` + c.Uid + ` and status=1`); isdefault == nil {
			input.Set("default", "1")
		}
		input.Set("addtime", sword.Gettimes(""))
	} else {
		if istrue := models.Query(`select id from mt_member_address where status=1 and uid=` + c.Uid + ` and id=` + id); istrue == nil {
			input.Set("id", "")
		}
	}
	if _, err := models.Save("mt_member_address", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}
	c.ServeJSON()
}

type MyAddressDefault struct {
	BaseController
}

func (c *MyAddressDefault) Get() {
	defer c.ServeJSON()
	if c.Uid != "" {
		id := c.GetString("id")
		if err := models.Query("update mt_member_address set `default`=0 where uid=" + c.Uid); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {
			if err = models.Query("update mt_member_address set `default`=1 where id=" + id); err != nil {
				beego.Debug(err)
				c.Data["json"] = 0
			} else {
				c.Data["json"] = 1
			}
		}
	} else {
		c.Data["json"] = 0
	}
}

type MyMoney struct {
	BaseController
}

func (c *MyMoney) Get() {

	info := models.Query(`select a.id,a.money,a.type from mt_member a where a.id=` + c.Uid)
	isshop := models.Query(`select id from mt_shop where status=1 and style=1 and censoring=1 and uid=` + c.Uid + ` limit 1`)
	if isshop == nil {
		info[0]["isshop"] = 0
	} else {
		info[0]["isshop"] = 1
	}
	c.Data["info"] = info[0]

	status := c.GetString("status")
	starttime := c.GetString("starttime")
	endtime := c.GetString("endtime")
	var w []string
	w = append(w, `a.uid=`+c.Uid)
	if status != "" {
		w = append(w, `a.type=`+status)
	}
	if starttime != "" {
		w = append(w, `a.addtime>'`+starttime+`'`)
	}
	if endtime != "" {
		w = append(w, `a.addtime<'`+endtime+`'`)
	}

	page, page2, num := models.Pagechange(c.GetString("page"), "10")
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.addtime desc`
	ws := strings.Join(w, ` and `)
	sql := `select a.id,a.type,a.money,a.oid,a.addtime,a.paytype,b.name as bname,c.pathname as bpathname 
	from mt_member_money_detail a 
	left join mt_systems_configuration b on a.bank=b.id 
	left join mt_resources c on b.img=c.id 
	where ` + ws + ob + lt
	info2 := models.Query(sql)
	for _, v := range info2 {
		t := fmt.Sprint(v["type"])
		oid := fmt.Sprint(v["oid"])
		paytype := fmt.Sprint(v["paytype"])
		switch t {
		case "0":
			switch paytype {
			case "2":
				v["name"] = "微信"
			case "3":
				v["name"] = "支付宝"
			}
		case "1":
			v["name"] = v["bname"]
		case "3":
			order := models.Query(`select a.id,a.ordernum,b.name,c.pathname from mt_order a left join mt_shop b on a.gid=b.id left join mt_resources c
			 on b.logo=c.id where a.id in(` + oid + `)`)
			v["product"] = order
		case "2", "4", "5":
			order := models.Query(`select b.monicker,c.pathname from mt_order a left join mt_member b on a.uid=b.id left join mt_resources c on b.avatar=c.id where a.id in(` + oid + `)`)
			v["name"] = order[0]["monicker"]
		case "6":
			order := models.Query(`select a.ordernum from mt_order a where a.id=` + oid)
			v["name"] = order[0]["ordernum"]
		case "7":
			order := models.Query(`select a.ordernum,c.pathname from mt_order a left join mt_member b on a.uid=b.id left join 
			mt_resources c on b.avatar=c.id where a.id=` + oid)
			v["name"] = order[0]["ordernum"]
		}
	}
	c.Data["list"] = info2
	sql2 := `select count(a.id) as totals from mt_member_money_detail a where ` + ws
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["status"] = status
	c.Data["endtime"] = endtime
	c.Data["starttime"] = starttime
	c.Data["url"] = `/my/money?status=` + status + `&starttime=` + starttime + `&endtime=` + endtime + `&`
	c.TplName = "pc/my/money/money.html"
}

type MyRecharge struct {
	BaseController
}

func (c *MyRecharge) Get() {
	c.TplName = "pc/my/money/recharge.html"
}
func (c *MyRecharge) Post() {
	defer c.ServeJSON()
	var js = make(map[string]interface{})
	c.Data["json"] = &js
	js["status"] = 1
	t := c.GetString("type")
	money, err := c.GetFloat("money")
	if err != nil {
		beego.Debug(err)
		js["status"] = 0
		return
	}
	if t == "1" {
		res := mobile.WxPay(c.Uid, "充值", c.Ctx.Input.IP(), "", money, 3, 1)
		if res != nil {
			js["res"] = res
		} else {
			js["status"] = 0
			return
		}
	} else {
		if res, err := mobile.Alipay(c.Uid, money, "", 1, 3); err != nil {
			beego.Debug(err)
			js["status"] = 0
			return
		} else {
			js["res"] = res
		}
	}
	// utils.Display("js", js)
}

type MyMoneyGetcash struct {
	BaseController
}

func (c *MyMoneyGetcash) Get() {
	info := models.Query(`select a.money,a.cashpassword,b.pathname from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + c.Uid)[0]
	bank := models.Query(`select a.id,a.name,b.pathname from mt_systems_configuration a left join mt_resources b on a.img=b.id where a.alias='getcash' and a.status=1`)
	c.Data["info"] = info
	c.Data["bank"] = bank
	c.TplName = "pc/my/money/getcash.html"
}

func (c *MyMoneyGetcash) Post() {
	defer c.ServeJSON()
	uid := c.Uid
	money := c.GetString("money")
	isok := models.Query(`select id,cashpassword from mt_member where money>=` + money + ` and id=` + uid)
	if isok == nil {
		c.Data["json"] = 2
		return
	}
	cashpassword := sword.ToMD5(c.GetString("cashpassword"))
	cashpassword2 := isok[0]["cashpassword"]
	if cashpassword != cashpassword2 {
		c.Data["json"] = 3
		return
	}
	isshop := models.Query(`select id from mt_shop where status=1 and censoring=1 and uid=` + c.Uid)
	if isshop != nil {
		money2 := sword.Sum(money, fmt.Sprint(models.Systems()["shopcash"]))
		if isenou := models.Query(`select id from mt_member where money>=` + money2 + ` and uid=` + c.Uid); isenou == nil {
			c.Data["json"] = 4
			return
		}
	}
	o := models.Orm()
	o.Begin()
	if _, err := o.Raw(`update mt_member set money=money-` + money + ` where id=` + uid).Exec(); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
		o.Rollback()
		return
	}
	sql := fmt.Sprintf(`insert into mt_member_getcash (uid,money,bank,account,name,addtime) values ('%v','%v','%v','%v','%v','%v')`,
		uid, money, c.GetString("bank"), c.GetString("account"), c.GetString("name"), sword.Gettimes(""))
	if _, err := o.Raw(sql).Exec(); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
		o.Rollback()
	} else {
		if _, err := o.Raw(fmt.Sprintf(`insert into mt_member_money_detail (uid,type,money,addtime,bank) values ('%v','%v','%v','%v','%v')`,
			uid, 1, money, sword.Gettimes(""), c.GetString("bank"))).Exec(); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			o.Rollback()
		} else {
			o.Commit()
			c.Data["json"] = 1
			bank := models.Query(`select name from mt_systems_configuration where id=` + c.GetString("bank"))[0]["name"]
			openid := models.Query(`select b.wx_openid_gzh from mt_systems a left join mt_member b on a.uid=b.id`)[0]["wx_openid_gzh"]
			data2 := map[string]map[string]interface{}{
				"first":    {"value": `您有一个新的提现申请`},
				"keyword1": {"value": c.GetString("name")},
				"keyword2": {"value": sword.Gettimes(""), "color": "#9c9c9c"},
				"keyword3": {"value": money, "color": "#e4393c"},
				"keyword4": {"value": bank},
				"remark":   {"value": `请您尽快处理~`},
			}
			models.Push(fmt.Sprint(openid), `JFrrx9CxZwepPyYz6VdwLRFa1e5xFbof3-DEGhtoEsI`, data2, "", "")
		}
	}

}

func (c *MyOrder) Post() {
	defer c.ServeJSON()
	var js = make(map[string]interface{})
	c.Data["json"] = &js
	oid := c.GetString("oid")
	paytype := c.GetString("paytype")
	js["type"] = paytype
	// if paytype == "1" {
	// 	password := c.GetString("password")
	// 	if password != "" {
	// 		paypassword := sword.ToMD5(password)
	// 		if ispok := models.Query(`select id from mt_member where paypassword='` + paypassword + `' and id=` + c.Uid); ispok == nil {
	// 			js["status"] = 3
	// 			return
	// 		}
	// 	}
	// }
	beego.Debug(111)
	if order := models.Query(`select ordernum,gid,money,addtime,carid from mt_order where uid=` + c.Uid + ` and id=` + oid + ` and status=1`); order != nil && paytype != "" {
		money := order[0]["money"].(string)
		nowtime := sword.Gettimes("")
		switch paytype {
		case "1":
			moneyen := models.Query(`select id from mt_member where money>=` + money + ` and id=` + c.Uid)
			if moneyen == nil {
				js["status"] = 2 //余额不足
				return
			}
			o := models.Orm()
			o.Begin()
			if _, err := o.Raw(`update mt_member set money=money-` + money + ` where id=` + c.Uid).Exec(); err != nil {
				beego.Debug(err)
				js["status"] = 0
				o.Rollback()
				return
			}
			if _, err := o.Raw(fmt.Sprintf(`update mt_order set status=2,paytime='%v' where id=%v`, nowtime, oid)).Exec(); err != nil {
				beego.Debug(err)
				js["status"] = 0
				o.Rollback()
				return
			}
			if _, err := o.Raw(fmt.Sprintf(`insert into mt_member_money_detail (uid,type,money,oid,addtime,paytype) values 
							('%v','%v','%v','%v','%v','%v')`, c.Uid, 3, money, oid, nowtime, paytype)).Exec(); err != nil {
				beego.Debug(err)
				js["status"] = 0
				o.Rollback()
				return
			}
			js["status"] = 1
			o.Commit()
			mobile.PayPush(oid)
		case "2":
			moneyf, _ := strconv.ParseFloat(money, 64)
			res := mobile.WxPay(c.Uid, "支付订单", c.Ctx.Input.IP(), oid, moneyf, 3, 0)
			beego.Debug(res)
			if res != nil {
				js["res"] = res
				js["status"] = 1
				js["oid"] = oid
			} else {
				js["status"] = 0
				return
			}
		case "3":
			moneyf, err := strconv.ParseFloat(money, 64)
			if err != nil {
				js["status"] = 0
				beego.Debug(err)
				return
			} else {
				if res, err := mobile.Alipay(c.Uid, moneyf, oid, 0, 3); err != nil {
					beego.Debug(err)
					js["status"] = 0
					return
				} else {
					js["res"] = res
				}
			}
		}
	} else {
		js["status"] = 0
	}
}

type MyOrderDetail struct {
	BaseController
}

func (c *MyOrderDetail) Get() {
	id := c.GetString("id")

	if id == "" {
		return
	}
	order := models.Query(`select a.*,b.pathname,z.name as shen,x.name as shi,c.name as qu,e.offer,g.name as gname,g.tel from mt_order a 
		left join mt_resources b on a.sendimg=b.id left join mt_member_coupon d on a.yid=d.id left join mt_coupon e on d.yid=e.id 
		left join mt_area z on a.province=z.code left join mt_area x on a.city=x.code left join mt_area c on a.area=c.code left join 
		mt_shop g on a.gid=g.id where a.id=` + id)[0]
	carid := fmt.Sprint(order["carid"])
	if carid == "" || carid == "<nil>" {
		carid = "''"
	}
	var shopcar []orm.Params
	shopcar = models.Query(`select a.pid,a.num,a.sendnum,a.status,b.title,b.spec,b.number,a.price,c.pathname,b.model,b.cid,a.uid,a.spec as spec2 from mt_order_car a 
			left join mt_product b on a.pid=b.id left join mt_resources c on b.img=c.id where a.id in(` + carid + `)`)
	var cids []string
	for _, v := range shopcar {
		cids = append(cids, v["cid"].(string))
	}
	cid := strings.Join(cids, ",")
	recommend := mobile.ProductList(`select a.id,a.title,a.price,a.mprice,b.pathname,a.isvip from mt_product a left join mt_resources b on a.img=b.id where a.cid in(`+cid+`) 
		and a.status=1 and a.censoring=1 order by a.recommend desc,a.sort desc,a.addtime desc limit 10`, c.Uid)
	order["shopcar"] = shopcar
	c.Data["order"] = order
	c.Data["recommend"] = recommend
	c.TplName = "pc/my/order/detail.html"
}

type MyOrderReturnApply struct {
	BaseController
}

func (c *MyOrderReturnApply) Get() {
	rid := c.GetString("rid")
	var id string
	var rinfo orm.Params
	if rid != "" {
		rinfo = models.Query(`select a.id,a.oid,a.why,b.name as wname,a.intr from mt_order_return a left join mt_systems_configuration b on a.why=b.id 
			where a.id=` + rid)[0]
		id = rinfo["oid"].(string)
	} else {
		id = c.GetString("id")
	}
	if order := models.Query(`select a.gid,a.id,a.money,a.count,a.carid,a.status,a.agid,a.type,a.goodtime,b.name as gname from mt_order a left join mt_shop b on a.gid=b.id 
			where a.status in(2,4,5) and a.id=` + id); order != nil {
		carid := fmt.Sprint(order[0]["carid"])
		shopcar := models.Query(`select a.pid,a.num,a.sendnum,a.status,a.uid,b.title,b.spec,b.number,a.price,c.pathname,b.model from mt_order_car a left join mt_product b on a.pid=b.id 
			left join mt_resources c on b.img=c.id where a.id in(` + carid + `)`)
		order[0]["shopcar"] = shopcar
		why := models.Query(`select id,name from mt_systems_configuration where status=1 and alias='why'`)
		status := fmt.Sprint(order[0]["status"])
		goodtime := fmt.Sprint(order[0]["goodtime"])
		var isre = 0
		//0 失效
		//1 退换货都支持
		//2 仅退货
		//3 仅换货
		if status == "4" {
			isre = 1
		} else if status == "5" {
			freight, _ := strconv.Atoi(fmt.Sprint(models.Systems()["freight"])) //换货期限
			exile, _ := strconv.Atoi(fmt.Sprint(models.Systems()["exile"]))     //退货期限
			timenow := time.Now().Local()
			loc, _ := time.LoadLocation("Local")
			timegood, _ := time.ParseInLocation(Tparse, goodtime, loc)
			timefreight := timegood.AddDate(0, 0, freight)
			timeexile := timegood.AddDate(0, 0, exile)
			if timenow.Before(timefreight) && timenow.Before(timeexile) {
				isre = 1
			} else if !timenow.Before(timefreight) && timenow.Before(timeexile) {
				isre = 2
			} else if timenow.Before(timefreight) && !timenow.Before(timeexile) {
				isre = 3
			}
		} else if status == "2" {
			isre = 2
		}

		if isre == 0 {
			return
		}
		order[0]["isre"] = isre
		c.Data["info"] = order[0]
		c.Data["why"] = why
		c.Data["rinfo"] = rinfo
		c.TplName = "pc/my/order/returnApply.html"

	} else {
		c.Ctx.Redirect(302, "/my/order")
	}
}

func (c *MyOrderReturnApply) Post() {
	defer c.ServeJSON()
	input := c.Input()
	order := models.Query(`select a.gid,a.addtime,a.status,a.money,a.ordernum,b.monicker,a.carid from mt_order a left join mt_member 
		b on a.uid=b.id where a.id=` + input.Get("oid"))[0]
	monicker := fmt.Sprint(order["monicker"])
	input.Del("id")
	input.Set("addtime", sword.Gettimes(""))
	input.Set("check", "0")
	input.Set("agree", "0")
	input.Set("id", c.GetString("rid"))
	input.Del("rid")
	shopcar := c.GetString("shopcar")

	shopcars := strings.Split(shopcar, ",")
	carid := fmt.Sprint(order["carid"])
	carids := strings.Split(carid, ",")
	for k, v := range carids {
		if err := models.Exec(`update mt_order_car set rnum=` + shopcars[k] + ` where id=` + v); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			return
		}
	}
	input.Del("shopcar")
	var first string
	if c.GetString("rid") == "" {
		input.Set("addtime", sword.Gettimes(""))
		first = monicker + `向您发起了一笔退款申请,请及时处理`
	} else {
		first = monicker + `重新提交了退款申请,请及时处理`
	}
	if _, err := models.Save("mt_order_return", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
		return
	} else {
		c.Data["json"] = 1
		if err = models.Exec(`update mt_order set status=6 where id=` + input.Get("oid")); err != nil {
			beego.Debug(err)
		}
	}
	gopenid := fmt.Sprint(models.Query(`select b.wx_openid_gzh from mt_systems a left join mt_member b on a.uid=b.id`)[0]["wx_openid_gzh"])
	data1 := map[string]map[string]interface{}{
		"first":    {"value": first},
		"keyword1": {"value": order["ordernum"], "color": `#36353A`},
		"keyword2": {"value": order["money"], "color": `#e31939`},
		"keyword3": {"value": order["addtime"], "color": "#36353A"},
		"remark":   {"value": `您可以进入后台城查看~`},
	}
	models.Push(gopenid, `L-BI2hpqu5MJ5sI0Rm8-j1jeTMmGAnU_oEYphIUPvCE`, data1, models.Urlc+"/mobile/index", "")

}

type MyOrderReturnDetail struct {
	BaseController
}

func (c *MyOrderReturnDetail) Get() {
	id := c.GetString("id")
	if re := models.Query(`select a.*,b.name as whys,c.ordernum,c.carid,c.agid,c.type as ctype,d.tel,c.money from mt_order_return a left join mt_systems_configuration b on a.why=b.id
		 left join mt_order c on a.oid=c.id left join mt_shop d on c.gid=d.id where a.status=1 and a.id=` + id); re != nil {
		for _, v := range re {
			v["gid"] = models.Query(`select b.gid from mt_order_car a join mt_product b on a.pid=b.id where a.id in(` + fmt.Sprint(v["carid"]) + `)`)[0]["gid"]
			product := models.Query(`select b.model,a.num,a.sendnum,a.status,b.id,a.price,b.title,b.number,b.spec,c.pathname,a.spec as spec2 from mt_order_car a left join mt_product b on a.pid=b.id left join mt_resources c 
		 			on b.img=c.id where a.id in(` + fmt.Sprint(v["carid"]) + `)`)
			// t := fmt.Sprint(v["ctype"])
			// agid := fmt.Sprint(v["agid"])
			v["product"] = product
		}
		if c.IsAjax() {
			// var js = make(map[string]interface{})
			// js["info"] = order[0]
			// js["why"] = why
			c.Data["json"] = re[0]
			c.ServeJSON()
		} else {
			c.Data["info"] = re[0]
			c.TplName = "pc/my/order/return_detail.html"
		}
	} else {
		if c.IsAjax() {
			c.StopRun()
		} else {
			c.Ctx.Redirect(302, "/my/order")
		}
	}
}
func (c *MyOrderReturnDetail) Post() {
	id := c.GetString("id")
	if err := models.Exec(`update mt_order_return set status=0 where id=` + id); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		re := models.Query(`select oid from mt_order_return where id=` + id)[0]
		oid := re["oid"].(string)
		if err := models.Exec(`update mt_order set status=5 where id=` + oid); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {
			c.Data["json"] = 1
		}
	}
	c.ServeJSON()
}

type MyCF struct {
	BaseController
}

func (c *MyCF) Get() {
	uri := c.Ctx.Request.RequestURI
	var w []string
	w = append(w, `a.uid=`+c.Uid)
	ob := ` order by a.addtime desc`
	var keyword = c.GetString("keywords")
	if uri == "/my/collect" {
		if keyword != "" {
			w = append(w, `b.title like '%`+keyword+`%'`)
		}
		ws := strings.Join(w, ` and `)
		sql := `select a.id,b.title,b.cid,a.pid,b.gid,c.pathname,b.price,b.isvip,b.issellnum,b.sellnum,b.keywords,b.minbuy,d.name as gname,e.name as shen from 
		mt_member_collection a join (select * from mt_product where censoring=1 and status=1) b on a.pid=b.id left join mt_resources c on b.img=c.id 
		left join mt_shop d on b.gid=d.id left join mt_area e on d.province=e.id where ` + ws + ob
		info := mobile.ProductList(sql, c.Uid)
		c.Data["info"] = info
		c.TplName = "pc/my/cf/collect.html"
	} else {
		if keyword != "" {
			w = append(w, `a.name like '%`+keyword+`%'`)
		}
		ws := strings.Join(w, ` and `)
		sql2 := `select a.id,a.gid from mt_member_focus a left join mt_shop b on a.gid=b.id where ` + ws + ob
		info2 := models.Query(sql2)
		for _, v := range info2 {
			gid := v["gid"].(string)
			if gid == "0" {
				sys := models.Systems()
				v["pathname"] = sys["pathname"]
				v["name"] = sys["name"]
				v["fw"] = "全品类"
				product := mobile.ProductList(`select a.id,b.pathname,a.sellnum,a.issellnum,a.isvip,a.price from mt_product a 
					left join mt_resources b on a.img=b.id 
					left join mt_shop c on a.gid=c.id 
					where a.censoring=1 and a.status=1 and (a.gid=0 or c.style=0) order by a.recommend desc,a.sort desc`, c.Uid)
				pnum := len(product)
				v["pnum"] = pnum
				if pnum >= 3 {
					v["product"] = product[0:3]
				} else {
					v["product"] = product
				}
			} else {
				sh := models.Query(`select a.name,b.pathname,a.type from mt_shop a left join mt_resources b on a.logo=b.id where a.id=` + gid)[0]
				v["pathname"] = sh["pathname"]
				v["name"] = sh["name"]
				t := fmt.Sprint(sh["type"])
				t = strings.Trim(t, ",")
				if t == "" {
					t = "''"
				}
				v["fw"] = models.Query(`select id,name from mt_column where id in (` + t + `)`)
				product := mobile.ProductList(`select a.id,b.pathname,a.sellnum,a.issellnum,a.isvip,a.price from mt_product a left join mt_resources b on a.img=b.id where 
				a.censoring=1 and a.status=1 and a.gid=`+gid+` order by a.grecommend desc,a.gsort desc`, c.Uid)
				pnum := len(product)
				v["pnum"] = pnum
				if pnum >= 3 {
					v["product"] = product[0:3]
				} else {
					v["product"] = product
				}
			}
			v["num"] = models.Query(`select count(a.id) as num from mt_member_focus a where gid=` + gid)[0]["num"]
			sellnum := models.Query(`select sum(a.num) as num from mt_order_car a where a.status>1 and a.gid=` + gid)[0]["num"]
			if sellnum == nil {
				v["sellnum"] = "0"
			} else {
				v["sellnum"] = sellnum
			}

		}
		c.Data["info"] = info2
		c.TplName = "pc/my/cf/focus.html"
	}
}

func (c *MyCF) Post() {
	id := c.GetString("id")
	table := c.GetString("table")
	if istrue := models.Query(`select id from ` + table + ` where id=` + id + ` and uid=` + c.Uid); istrue != nil {
		if err := models.Exec(`delete from ` + table + ` where id=` + id); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {
			c.Data["json"] = 1
		}
	} else {
		c.Data["json"] = 0
	}
	c.ServeJSON()
}

type MyCoupon struct {
	BaseController
}

func (c *MyCoupon) Get() {
	var w []string
	w = append(w, `a.uid=`+c.Uid)
	w = append(w, `a.status=1`)
	w = append(w, `b.endtime>'`+sword.Gettimes("")+`'`)
	ob := ` order by a.addtime desc`
	ws := strings.Join(w, ` and `)
	sql := `select a.id,b.name,b.offer,b.full,date_format(b.starttime,'%Y-%m-%d') as starttime,date_format(b.endtime,'%Y-%m-%d') as endtime,
	a.addtime,c.name as gname,d.pathname,b.gid from 
		mt_member_coupon a left join mt_coupon b on a.yid=b.id left join mt_shop c on b.gid=c.id 
		left join mt_resources d on b.img=d.id where ` + ws + ob
	info := models.Query(sql)
	c.Data["info"] = info
	c.TplName = "pc/my/money/coupon.html"

}

type MyComplate struct {
	BaseController
}

func (c *MyComplate) Get() {
	if isp := models.Query(`select id from mt_shop where censoring=1 and status=1 and style=0 and uid=` + c.Uid); isp != nil {
		sid := fmt.Sprint(isp[0]["id"])
		var w []string
		w = append(w, `c.status>1`)
		ws := strings.Join(w, ` and `)
		page, page2, num := models.Pagechange(c.GetString("page"), "")
		lt := ` limit ` + page + `,` + num
		ob := ` order by c.paytime desc`
		sql := `select c.id,c.carid,c.ordernum,c.addtime 
		from mt_order c 
		join mt_order_car a on a.id in(c.carid) 
		join (select * from mt_product where gid=` + sid + `) b on a.pid=b.id 
		where ` + ws + ob + lt
		sql2 := `select count(a.id) as totals from mt_order c 
		join mt_order_car a on a.id in(c.carid) 
		join (select * from mt_product where gid=` + sid + `) b on a.pid=b.id 
		where ` + ws
		c.Data["paginator"] = models.Page(sql2, page2, num)
		info := models.Query(sql)
		for _, i := range info {
			carid := fmt.Sprint(i["carid"])
			shopcar := models.Query(`select a.num,a.status,a.id,a.sendnum,a.pid,b.title,b.length,b.width,b.model, 
				b.height,b.weight,b.number,b.spec,b.isw,d.monicker,c.pathname,e.pathname as path 
				from mt_order_car a 
				join (select * from mt_product where gid=` + sid + `) b on a.pid=b.id 
				left join mt_member d on a.did=d.id 
				left join mt_resources c on d.avatar=c.id 
				left join mt_resources e on b.img=e.id 
				where a.id in(` + carid + `) order by a.paytime`)
			var we = "0.00"
			var volume = "0.00"
			for _, v := range shopcar {
				isw := fmt.Sprint(v["isw"])
				width := fmt.Sprint(v["width"])
				height := fmt.Sprint(v["height"])
				length := fmt.Sprint(v["length"])
				weight := fmt.Sprint(v["weight"])
				if isw == "0" {
					volume = sword.Sum(volume, sword.Mult(length, sword.Mult(height, width)))
				} else {
					we = sword.Sum(we, weight)
				}
			}
			i["we"] = we
			i["volume"] = sword.Divi(volume, "1000000")
			i["shopcar"] = shopcar
		}
		c.Data["info"] = info
		c.TplName = "pc/my/complate/complate.html"
	} else {
		c.StopRun()
	}
}

func (c *MyComplate) Post() {
	defer c.ServeJSON()
	id := c.GetString("id")
	oid := c.GetString("oid")
	num := c.GetString("num")
	openid := models.Query(`select c.wx_openid_gzh,a.ordernum from mt_order a left join mt_member b on a.uid=b.id
		 left join mt_member c on b.sid=c.id where a.id=` + oid)[0]
	if num == "" {
		if err := models.Exec(`update mt_order_car set sendnum=num,status=3 where id=` + id); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {
			c.Data["json"] = 1
		}
	} else {
		if is := models.Query(`select id from mt_order_car where num>=` + num + ` and id=` + id); is != nil {
			if err := models.Exec(`update mt_order_car set sendnum=num-` + num + `,status=3 where id=` + id); err != nil {
				beego.Debug(err)
				c.Data["json"] = 0
			} else {
				c.Data["json"] = 1
			}
			openids := fmt.Sprint(openid["wx_openid_gzh"])
			product := models.Query(`select b.title from mt_order_car a left join mt_product b on a.pid=b.id where a.id=` + id)[0]["title"].(string)
			data3 := map[string]map[string]interface{}{
				"first":    {"value": `有笔订单缺货提醒`},
				"keyword1": {"value": openid["ordernum"], "color": `#36353A`},
				"keyword2": {"value": sword.Gettimes(""), "color": "#9c9c9c"},
				"keyword3": {"value": product + ` x ` + num, "color": `#e31939`},
				"remark":   {"value": `请您尽快联系客户,说明情况`},
			}
			models.Push(openids, `HDTqyPEaJhm9GJYf6sdLPEoWGx9F5bRQNEH6uBTL0Dg`, data3, models.Urlc+"/mobile/index", "")
		} else {
			c.Data["json"] = 0
		}
	}
	if c.Data["json"].(int) == 1 {
		//提货推送
		shop := models.Query(`select c.*,b.title,a.sendnum,a.did from mt_order_car a join mt_product b on a.pid=b.id join mt_shop c on b.gid=c.id where a.id=` + id)
		if shop == nil {
			//待分配
			return
		}
		if fmt.Sprint(shop[0]["did"]) == "" || fmt.Sprint(shop[0]["did"]) == "0" || fmt.Sprint(shop[0]["did"]) == "<nil>" {
			area := fmt.Sprint(shop[0]["area"])
			driver := models.Query(`select id,wx_openid_gzh from mt_member where driver=1 and status=1 and driverarea=` + area)
			if driver != nil {
				if err := models.Exec(`update mt_order_car set did=` + driver[0]["id"].(string)); err != nil {
					beego.Debug(err)
					return
				}
				data4 := map[string]map[string]interface{}{
					"first":    {"value": fmt.Sprintf(`您需要提取 %v x %v`, shop[0]["title"], shop[0]["sendnum"])},
					"keyword1": {"value": openid["ordernum"], "color": `#36353A`},
					"keyword2": {"value": shop[0]["name"], "color": "#e31939"},
					"keyword3": {"value": shop[0]["address"], "color": `#333`},
					"keyword4": {"value": sword.Gettimes(""), "color": `#9c9c9c`},
					"remark":   {"value": `请您尽快前往提货`},
				}
				models.Push(fmt.Sprint(driver[0]["wx_openid_gzh"]), `erYqlXpwON3LAZ7oVmwWgV27mDQCYJbsuxSpkevQyVA`, data4, models.Urlc+"/mobile/my", "")
			}
		}
	}
}

type MyOrderConfirm struct {
	BaseController
}

func (c *MyOrderConfirm) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	istrue := models.Query(`select id from mt_order where status=3 and uid=` + c.Uid + ` and id=` + id)
	if istrue == nil {
		c.Data["json"] = 0
		return
	}
	if err := mobile.OrderConfirmF(id); err != nil {
		c.Data["json"] = 0
		beego.Debug(err)
		return
	}
	c.Data["json"] = 1
}

type MyOrderEvaluation struct {
	BaseController
}

func (c *MyOrderEvaluation) Get() {
	id := c.GetString("id")
	if istrue := models.Query(`select id,carid from mt_order where status=4 and uid=` + c.Uid + ` and id=` + id); istrue != nil {
		carid := fmt.Sprint(istrue[0]["carid"])
		shopcar := models.Query(`select a.id,b.title,c.pathname from mt_order_car a left join mt_product b on a.pid=b.id left join mt_resources c 
				on b.img=c.id where a.id in(` + carid + `)`)
		c.Data["shopcar"] = shopcar
		c.TplName = "pc/my/order/evaluateAdd.html"
	} else {

		c.Ctx.Redirect(302, "/mobile/my")
	}
}

func (c *MyOrderEvaluation) Post() {
	defer c.ServeJSON()
	id := c.GetString("id")
	if istrue := models.Query(`select id,gid from mt_order where status=4 and uid=` + c.Uid + ` and id=` + id); istrue != nil {
		style := c.GetString("style")
		score := c.GetStrings("score")
		cid := c.GetStrings("cid")
		content := c.GetStrings("content")
		img := c.GetStrings("img")
		if style == "2" {
			cid = strings.Split(c.GetString("cid"), ",")
			score = strings.Split(c.GetString("score"), ",")
			img = strings.Split(c.GetString("img"), ",")
			content = strings.Split(c.GetString("content"), ",")
		}
		shop_score := c.GetString("shop_score")
		shop_logisticsscore := c.GetString("shop_logisticsscore")
		// utils.Display("cid", cid)
		// utils.Display("img", img)
		// utils.Display("score", score)
		// utils.Display("content", content)
		o := models.Orm()
		o.Begin()
		nowtime := sword.Gettimes("")
		if _, err := o.Raw(fmt.Sprintf(`insert into mt_shop_evaluation (uid,gid,score,logisticsscore,addtime) values (%v,%v,%v,%v,'%v')`,
			c.Uid, 0, shop_score, shop_logisticsscore, nowtime)).Exec(); err != nil {
			beego.Debug(err)
			o.Rollback()
			c.Data["json"] = 0
			return
		}
		for k, v := range cid {
			imgs := strings.Trim(img[k], ",")
			// var content string
			// if content[k]==""{
			// 	content="这个买家很酷,什么都没有留下~"
			// }
			sql := fmt.Sprintf(`insert into mt_product_evaluation (uid,cid,content,img,score,addtime) values (%v,%v,'%v','%v',%v,'%v')`,
				c.Uid, v, content[k], imgs, score[k], nowtime)
			if _, err := o.Raw(sql).Exec(); err != nil {
				beego.Debug(err)
				o.Rollback()
				c.Data["json"] = 0
				return
			}
		}
		if _, err := o.Raw(`update mt_order set status=5 where id=` + id).Exec(); err != nil {
			beego.Debug(err)
			o.Rollback()
			c.Data["json"] = 0
			return
		}
		o.Commit()
		c.Data["json"] = 1
	} else {
		c.Data["json"] = 2
	}
}

type MyMessage struct {
	BaseController
}

func (c *MyMessage) Get() {
	uid := c.Uid
	sql := `select * from mt_sms where id in (select max(a.id) from mt_sms a where (fid=` + uid + ` or uid=` + uid + `) and uid<>0 and fid<>0 and 
	status=1 group by (a.fid+a.uid)) order by addtime desc`
	info := models.Query(sql)
	for _, v := range info {
		fid := v["fid"].(string)
		sid := v["uid"].(string)
		if uid == fid {
			v["member"] = models.Query(`select a.monicker,b.pathname,a.id from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + sid)[0]
		} else {
			v["member"] = models.Query(`select a.monicker,b.pathname,a.id from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + fid)[0]
		}
		fidi, _ := strconv.Atoi(fid)
		sidi, _ := strconv.Atoi(sid)
		idsum := fidi + sidi
		v["noread"] = models.Query(fmt.Sprintf(`select count(*) as num from mt_sms where uid+fid=%v and uid=%v and state=0 and status=1`, idsum, uid))[0]["num"]
	}
	c.Data["json"] = info
	if c.IsAjax() {
		c.ServeJSON()
	} else {
		c.TplName = "wechat/my/message.html"
	}
}

type MyMessageContent struct {
	BaseController
}

func (c *MyMessageContent) Get() {
	page, _, num := models.Pagechange(c.GetString("page"), "20")
	uid := c.Uid

	id := c.GetString("id")
	lt := ` limit ` + page + `,` + num
	sql := `select a.* from (select * from mt_sms where (uid=` + id + ` and fid=` + uid + `) or
		 (uid=` + uid + ` and fid=` + id + `) order by id desc ` + lt + `) a order by a.id`
	info := models.Query(sql)
	first := models.Query(`select a.monicker,a.id,b.pathname from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + uid)[0]
	second := models.Query(`select a.monicker,a.id,b.pathname from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + id)[0]
	if err := models.Exec(fmt.Sprintf("update mt_sms set state=1 where uid=%v and fid+uid=%v", uid, sword.Sum(id, uid))); err != nil {
		beego.Debug("打开聊天详情设为已读失败：", err)
	}
	if c.IsAjax() {
		var js = make(map[string]interface{})
		js["uid"] = uid
		js["info"] = info
		js["first"] = first
		js["second"] = second
		c.Data["json"] = js
		c.ServeJSON()
	} else {
		c.Data["uid"] = uid
		c.Data["first"] = first
		c.Data["second"] = second
		c.Data["json"] = info
		c.TplName = "wechat/my/message_content.html"
	}
}

type MyInfo struct {
	BaseController
}

func (c *MyInfo) Get() {
	info := models.Query(`select a.monicker,a.avatar,a.sex,a.name,a.wechat,a.mail,b.pathname 
		from mt_member a 
		left join mt_resources b on a.avatar=b.id 
		where a.id=` + c.Uid)[0]
	c.Data["info"] = info
	c.TplName = "pc/my/info/info.html"
}

func (c *MyInfo) Post() {
	input := c.Input()
	input.Set("id", c.Uid)
	if _, err := models.Save(`mt_member`, input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}
	c.ServeJSON()
}

type MySafe struct {
	BaseController
}

func (c *MySafe) Get() {
	info := models.Query(`select a.password,a.paypassword,a.cashpassword,a.mail,a.monicker,a.mobile from mt_member a where a.id=` + c.Uid)[0]
	mobiles := strings.Split(fmt.Sprint(info["mobile"]), "")
	var m []string
	for k, v := range mobiles {
		if k >= 3 && k < 7 {
			m = append(m, "*")
		} else {
			m = append(m, v)
		}
	}
	info["mobile"] = strings.Join(m, "")
	c.Data["info"] = info
	c.TplName = "pc/my/info/safe.html"
}

type MyPassword struct {
	BaseController
}

func (c *MyPassword) Get() {
	c.TplName = "pc/my/info/password.html"
}

func (c *MyPassword) Post() {
	t := c.GetString("type")
	var pt string
	switch t {
	case "login":
		pt = "password"
	case "pay":
		pt = "paypassword"
	case "cash":
		pt = "cashpassword"
	default:
		c.StopRun()
	}
	info := models.Query(`select a.password,a.paypassword,a.cashpassword from mt_member a where a.id=` + c.Uid)[0]
	oldpwd := sword.ToMD5(c.GetString("oldpwd"))
	newpwd := sword.ToMD5(c.GetString("newpwd"))

	if fmt.Sprint(info[pt]) == "" || fmt.Sprint(info[pt]) == "<nil>" {
		if err := models.Exec(`update mt_member set ` + pt + `='` + newpwd + `' where id=` + c.Uid); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {
			c.Data["json"] = 1
		}
	} else {
		if fmt.Sprint(info[pt]) == oldpwd {
			if err := models.Exec(`update mt_member set ` + pt + `='` + newpwd + `' where id=` + c.Uid); err != nil {
				beego.Debug(err)
				c.Data["json"] = 0
			} else {
				c.Data["json"] = 1
			}
		} else {
			c.Data["json"] = 2
		}
	}
	c.ServeJSON()
}

type MyInvoice struct {
	BaseController
}

func (c *MyInvoice) Get() {
	info := models.Query(`select * from mt_order_invoice where uid=` + c.Uid)
	if info != nil {
		c.Data["info"] = info[0]
	}
	c.TplName = "pc/my/info/invoice.html"
}
func (c *MyInvoice) Post() {
	input := c.Input()
	input.Set("uid", c.Uid)
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes(""))
	}
	if _, err := models.Save("mt_order_invoice", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}
	c.ServeJSON()
}

type MyIntegral struct {
	BaseController
}

func (c *MyIntegral) Get() {
	integral := models.Query(`select integral from mt_member where id=` + c.Uid + ` limit 1`)[0]["integral"]
	sb := sword.NewSqlBuilder()
	sb.Select("a.title", "a.id", "a.design", "a.integral", "b.pathname", "a.num")
	sb.From("mt_product_integral a")
	sb.LeftJoinOn("mt_resources b on a.img=b.id")
	sb.Where("a.status=1", "a.censoring=1")
	sb.OrderBy("a.sort desc")
	sb.Limit("12")
	product := models.Query(sb.String())
	c.Data["integral"] = integral
	c.Data["product"] = product
	c.TplName = "pc/my/money/integral.html"
}

func (c *MyIntegral) Post() {
	defer c.ServeJSON()
	var id = c.GetString("id")
	pro := models.Query(`select num,integral from mt_product_integral where id=` + id)[0]
	number, _ := strconv.Atoi(pro["num"].(string))
	integral := pro["integral"].(string)
	dnumber, _ := strconv.Atoi(models.Query(`select count(id) as number from mt_member_integral where pid=` + id)[0]["number"].(string))
	if number > dnumber {
		if en := models.Query(`select id from mt_member where integral>` + integral + ` and id=` + c.Uid); en != nil {
			o := models.Orm()
			o.Begin()
			if _, err := o.Raw(`update mt_member set integral=integral-` + integral + ` where id=` + c.Uid).Exec(); err != nil {
				beego.Debug(err)
				o.Rollback()
				c.Data["json"] = 0
				return
			}
			if _, err := o.Raw(`insert mt_member_integral (uid,type,number,addtime,pid) values (` + c.Uid + `,1,` + integral + `,'` + sword.Gettimes("") + `',` + id + `)`).Exec(); err != nil {
				beego.Debug(err)
				o.Rollback()
				c.Data["json"] = 0
				return
			}
			o.Commit()
			c.Data["json"] = 1
		} else {
			c.Data["json"] = 3
		}
	} else {
		c.Data["json"] = 2
	}
}

type MyIntegralRule struct {
	BaseController
}

func (c *MyIntegralRule) Get() {
	help := models.Query(`select id,name,content from mt_page where cid=294 and status=1 order by sort desc,addtime desc limit 1`)
	if help == nil {
		return
	}
	if c.IsAjax() {
		c.Data["json"] = help[0]
		c.ServeJSON()
	} else {
		c.Data["info"] = help[0]
		c.TplName = "wechat/my/integral_rule.html"
	}
}

type MyIntegralList struct {
	BaseController
}

func (c *MyIntegralList) Get() {
	var w []string
	w = append(w, `a.uid=`+c.Uid)
	status := c.GetString("status")
	starttime := c.GetString("starttime")
	endtime := c.GetString("endtime")
	if status != "" {
		w = append(w, `a.type=`+status)
	}
	if starttime != "" {
		w = append(w, `a.addtime>'`+starttime+`'`)
	}
	if endtime != "" {
		w = append(w, `a.addtime<'`+endtime+`'`)
	}
	ws := strings.Join(w, ` and `)
	integral := models.Query(`select integral from mt_member where id=` + c.Uid + ` limit 1`)[0]["integral"]
	page, page2, num := models.Pagechange(c.GetString("page"), "20")
	sb := sword.NewSqlBuilder()
	sb.Select("a.type", "a.id", "a.addtime", "a.number", "b.title", "c.ordernum", "a.oid")
	sb.From("mt_member_integral a")
	sb.LeftJoinOn("mt_product_integral b on a.pid=b.id", "mt_order c on a.oid=c.id")
	sb.Where(ws)
	sb.OrderBy("a.addtime desc")
	sb.Limit(num)
	sb.Offset(page)
	info := models.Query(sb.String())
	sql2 := `select count(a.id) as totals from mt_member_integral a where ` + ws
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["integral"] = integral
	c.Data["info"] = info
	c.Data["status"] = status
	c.Data["endtime"] = endtime
	c.Data["starttime"] = starttime
	c.Data["url"] = `/my/integral_list?status=` + status + `&starttime=` + starttime + `&endtime=` + endtime + `&`
	c.TplName = "pc/my/money/integralList.html"
}

type MyShopAdd struct {
	BaseController
}

func (c *MyShopAdd) Get() {
	if is := models.Query(`select a.type,a.logo,a.intr,a.name,a.businesslicense,a.person,a.license,a.cardimg,a.theimg,a.province,a.city,a.area,a.tel,
		b.pathname as lpath,c.pathname as cpath,d.pathname as tpath,e.pathname,f.name as shen,g.name as shi,h.name as qu from mt_shop_add a 
		left join mt_resources b on a.license=b.id left join mt_resources c on a.cardimg=c.id left join mt_resources d on a.theimg=d.id left join
		 mt_resources e on a.logo=e.id left join mt_area f on a.province=f.code left join mt_area g on a.city=g.code left join mt_area h on a.area=h.code
		  where a.uid=` + c.Uid + ` and censoring=2`); is != nil {
		c.Data["json"] = is[0]
	}
	if c.IsAjax() {
		c.ServeJSON()
	} else {
		c.TplName = "pc/my/shop_add.html"
	}
}
func (c *MyShopAdd) Post() {
	input := c.Input()
	id := input.Get("id")
	if id == "" {
		input.Set("addtime", sword.Gettimes(""))
	}
	input.Set("uid", c.Uid)
	if _, err := models.Save("mt_shop_add", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		m := models.Query(`select monicker from mt_member where id=` + c.Uid)[0]
		openid := models.Query(`select b.wx_openid_gzh from mt_systems a left join mt_member b on a.uid=b.id`)[0]["wx_openid_gzh"].(string)
		data2 := map[string]map[string]interface{}{
			"first":    {"value": `您有一个新的商户申请`},
			"keyword1": {"value": m["monicker"], "color": "#e4393c"},
			"keyword2": {"value": c.GetString("name")},
			"keyword3": {"value": sword.Gettimes(""), "color": "#9c9c9c"},
			"remark":   {"value": `请您尽快处理~`},
		}
		models.Push(openid, `JFrrx9CxZwepPyYz6VdwLRFa1e5xFbof3-DEGhtoEsI`, data2, "", "")
	}
	c.ServeJSON()
}

type MyOrderPush struct {
	BaseController
}

func (c *MyOrderPush) Get() {
	defer c.ServeJSON()
	id := c.GetString("id")
	now := sword.Gettimes("2006-01-02") + " 00:00:00"
	c.Data["json"] = 1
	if is := models.Query(`select id from mt_order_push where oid=` + id + ` and addtime>'` + now + `'`); is != nil {
		c.Data["json"] = 2
		return
	}
	if err := models.Exec(`insert into mt_order_push (oid,addtime) values(` + id + `,'` + sword.Gettimes("") + `')`); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
		return
	}
	order := models.Query(`select a.ordernum,a.gid,a.money from mt_order a where a.id=` + id)[0]
	data1 := map[string]map[string]interface{}{
		"first":    {"value": `您收到了一条催单提醒`},
		"keyword1": {"value": order["ordernum"], "color": `#36353A`},
		"keyword2": {"value": `待发货`, "color": `#e31939`},
		"keyword3": {"value": order["money"], "color": "#36353A"},
		"remark":   {"value": `请您尽快发货~`},
	}
	var gid = fmt.Sprint(order["gid"])
	var openid string
	if gid == "0" {
		openid = fmt.Sprint(models.Query(`select b.wx_openid_gzh from mt_systems a left join mt_member b on a.uid=b.id`)[0]["wx_openid_gzh"])
	} else {
		openid = fmt.Sprint(models.Query(`select b.wx_openid_gzh from mt_shop a left join mt_member b on a.uid=b.id`)[0]["wx_openid_gzh"])
	}
	models.Push(openid, `vxLbkepVf6pnXs3__9sIspnGAW-PK2woD7BQFki8pyA`, data1, models.Urlc+"/mobile/my/order_manage", "")
}
